<script src="https://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js"></script>
<template>
  <div>
    <div class="login-wrap">
      <!-- -----------------------添加dialog------------------------------------------------------ -->
      <el-dialog title="添加用户" :visible.sync="dialog.addshow" width="30%">
        <el-form ref="form" :model="form" label-width="80px">
          <el-form-item label="昵称">
            <el-input
              placeholder="请输入内容"
              v-model="form.userName"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="密码">
            <el-input
              placeholder="请输入内容"
              v-model="form.userPassword"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="手机">
            <el-input
              placeholder="请输入内容"
              v-model="form.userPhone"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="年龄">
            <el-input
              placeholder="请输入年龄"
              v-model="form.userAge"
            ></el-input>
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input
              placeholder="我的邮箱"
              v-model="form.userEmail"
            ></el-input>
          </el-form-item>
          <el-form-item label="真实姓名">
            <el-input
              placeholder="真实姓名"
              v-model="form.userRealName"
            ></el-input>
          </el-form-item>
          <el-form-item label="身份证号">
            <el-input
              placeholder="身份证号"
              v-model="form.userIdCard"
            ></el-input>
          </el-form-item>
          <el-form-item label="出生日期">
            <div class="block">
              <span class="demonstration"></span>
              <el-date-picker
                v-model="form.date"
                type="date"
                placeholder="选择日期"
              >
              </el-date-picker>
            </div>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">立即创建</el-button>
            <el-button>取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
      <!--输入框-->
      <div class="form-wrapper">
        <div class="header">
          PettyLoan<br /><span @click="goStaff">新橙定制</span>
        </div>
        <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
          <el-tab-pane label="密码登录" name="first">
            <div class="input-wrapper">
              <div class="border-wrapper">
                <input
                  type="text"
                  v-model="login.userAccount"
                  name="username"
                  placeholder="请输入账号/邮箱/手机号"
                  class="border-item"
                  autocomplete="off"
                />
              </div>
              <div class="border-wrapper">
                <input
                  type="password"
                  v-model="login.userPassword"
                  name="password"
                  placeholder="请输入密码"
                  class="border-item"
                  autocomplete="off"
                />
              </div>
            </div>
            <div class="action">
              <div class="btn" @click="loginDo">登录</div>
              <div class="btn" @click="registerDo">注册</div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="短信登录" name="second">
            <div class="input-wrapper">
              <div class="border-wrapper">
                <input
                  prop="phone"
                  :rules="phoneRules"
                  ref="phoneForm"
                  type="text"
                  v-model="phoneForm.phone"
                  name="username"
                  placeholder="请输入手机号"
                  class="border-item"
                  autocomplete="off"
                />
              </div>
              <div class="border-wrapper">
                <input
                  type="password"
                  v-model="phoneForm.smsCode"
                  name="password"
                  placeholder="短信验证码"
                  class="border-item"
                  autocomplete="off"
                />
              </div>
            </div>
            <div class="action">
              <!--<div class="btn" @click="sendCode()"  :disabled="getCodeBtnDisable">{{ smsBtn }}</div>-->
              <el-button
                class="btn"
                style="background-color: unset"
                @click="sendCode()"
                :disable="useButton"
                >{{ smsBtn }}</el-button
              >
              <el-button
                class="btn"
                style="background-color: unset"
                @click="smsLogin()"
                >登 录</el-button
              >
            </div>
          </el-tab-pane>
          <el-tab-pane label="员工登录" name="third">
            <div class="input-wrapper">
              <div class="border-wrapper">
                <input
                  type="text"
                  v-model="login.staffAccount"
                  name="username"
                  placeholder="请输入员工账号/邮箱/手机号"
                  class="border-item"
                  autocomplete="off"
                />
              </div>
              <div class="border-wrapper">
                <input
                  type="password"
                  v-model="login.staffPassword"
                  name="password"
                  placeholder="请输入员工密码"
                  class="border-item"
                  autocomplete="off"
                />
              </div>
            </div>
            <div class="action">
              <div class="btn" id="login_container" @click="handLoginByWx">扫码登录</div>
              <div class="btn" @click="loginStaff">登录</div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </div>
</template>
<script src="https://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js"></script>
  <script>
export default {
  data() {
    let checkPhone = (rule, value, callback) => {
      let reg = /^1[3|4|5|7|8][0-9]\d{8}$/;
      if (reg.test(value)) {
        return callback();
      }
      callback(new Error("请输入正确的手机号"));
    };
    return {
      phoneForm: {
        phone: "",
        code: "",
      },
      phoneRules: {
        phone: [
          {
            required: true,
            message: "请输入正确的联系方式",
            trigger: "blur",
            validator: checkPhone,
            trigger: "blur",
          },
        ],
        smsCode: [
          { required: true, message: "验证码不能为空", trigger: "blur" },
        ],
      },
      codeBtnWord: "获取验证码", // 获取验证码按钮文字
      waitTime: 60, // 获取验证码按钮失效时间
      useButton: false,

      smsBtn: "发送验证码",
      checked: true,
      activeName: "first",
      form: {},
      login: {},
      dialog: {
        addshow: false,
      },
      addForm: {},
      upload: {
        headerObj: "",
      },
      addForm: {},
      user: {},
      upload: {
        headerObj: "",
      },
    };
  },
  methods: {
    openMa() {

      var obj = new WxLogin({
        self_redirect: true,
        id: "login_container",
        appid: "wx59eaa87e98a9f5fb",
        scope: "snsapi_login",
        redirect_uri: "http://server.natappfree.cc/staffs/loginByWeChat",
        state: "",
        style: "",
        href: "",
      });
    },
    handLoginByWx() {
        // 重定向地址重定到当前页面，在路径获取code
        const hrefUrl = window.location.href
        // 判断是否已存在code
        if (!this.code) {
        // 不存在，配置相关微信登录参数（主要是授权页面地址，appID，回调地址）
          window.location.href = `
          	https://open.weixin.qq.com/connect/qrconnect
			?appid=wx59eaa87e98a9f5fb
			&redirect_uri=http://d2umkd.natappfree.cc/staffs/loginByWeChat
			&response_type=code
			&scope=snsapi_login
					`
        }
      },

    loginStaff() {
      this.$axios.post("/staffs/loginDo", this.login).then((response) => {
        if (response.data.code == 200) {
          this.$router.push("/Index");
          sessionStorage.setItem(
            "staff",
            JSON.stringify(response.data.data.staff)
          );
          sessionStorage.setItem(
            "menulist",
            JSON.stringify(response.data.data.menulist)
          );
        } else {
          this.$message.error("账号或密码有误，请检查后重新登录");
        }
      });
    },
    //发送短信验证码

    // async sendCode() {
    //   try {
    //     let params = {}
    //     params.phone = this.phoneForm.phone
    //     let data = await axios.get("/users/send/"+params.phone)
    //     this.$message.success('验证码发送成功')
    //     let that = this
    //     that.waitTime--
    //     that.getCodeBtnDisable = true
    //     this.smsBtn = `${this.waitTime}s 后重新发送`
    //     let timer = setInterval(function () {
    //       if (that.waitTime > 1) {
    //         that.waitTime--
    //         that.smsBtn = `${that.waitTime}s 后重新发送`
    //       } else {
    //         clearInterval(timer)
    //         that.smsBtn = '获取验证码'
    //         that.getCodeBtnDisable = false
    //         that.waitTime = 60
    //       }
    //     }, 1000)
    //   } catch (res) {
    //     console.log(res)
    //   }
    // },

    sendCode(phoneForm) {
      this.$axios
        .get("/users/send/" + this.phoneForm.phone)
        .then((response) => {
          if (response.data.code == 200) {
            this.$message.success("验证码发送成功，请及时登录");
            this.waitTime--;
            this.useButton = true;
            this.smsBtn = `${this.waitTime}s 后重新发送`;
            let timer = setInterval(function () {
              if (that.waitTime > 1) {
                this.waitTime--;
                this.smsBtn = `${this.waitTime}s 后重新发送`;
              } else {
                clearInterval(timer);
                this.smsBtn = "获取验证码";
                this.useButton = false;
                this.waitTime = 60;
              }
            }, 1000);
          }
        });
    },

    // sendCode(phoneForm) {
    //   this.$refs[phoneForm].validateField("phone", (valid) => {
    //     if (valid) {
    //       this.$message({
    //         message: "手机号格式错误",
    //       });
    //       return;
    //     } else {
    //       this.time = 60;
    //       document.getElementById("btn").disabled = true;

    //       let smsInfo = {
    //         phone: this.phoneForm.phone,
    //         smsCode: this.phoneForm.smsCode,
    //       };
    //       this.$api.login
    //         .smsCode(JSON.stringify(smsInfo))
    //         .then((res) => {
    //           if (res.code == 200) {
    //             this.$message.success("发送成功");
    //             let timer = setInterval(() => {
    //               this.time--;
    //               this.smsBtn = `${this.time}s重新发送`;
    //               if (this.time === 0) {
    //                 this.smsBtn = "重新发送";
    //                 document.getElementById("btn").disabled = false;
    //                 this.time = 60;
    //                 clearInterval(timer);
    //                 timer = null;
    //               }
    //             }, 1000);
    //           } else {
    //             this.$message({
    //               message: "发送失败" + res.msg,
    //               type: "error",
    //             });
    //             //this.reload();
    //           }
    //         })
    //         .catch(function (res) {
    //           alert(res);
    //         });
    //     }
    //   });
    // },
    smsLogin() {
      this.$axios.post("/users/smsLogin", this.phoneForm).then((response) => {
        if (response.data.code == 200) {
          this.$message.success("登录成功");
          this.$router.push("/Index");
          sessionStorage.setItem(
            "user",
            JSON.stringify(response.data.data.user)
          );
        } else if (response.data.code == 666) {
          this.$message.error(response.data.message);
        } else {
          this.$message.error(response.data.message);
        }
      });
    },
    handleClick(tab, event) {
      console.log(tab, event);
    },
    // 注册方法
    onSubmit() {
      this.$axios.post("/users/add", this.form).then((response) => {
        if (response.data.code == 200) {
          this.$router.push("/Index");
          // console.log(response.data.data.user);
          this.$store.commit("SET_USERINFO", response.data.data);
          this.$router.push(
            "/index/?userName=" + response.data.data.user.userName
          );
          sessionStorage.setItem(
            "user",
            JSON.stringify(response.data.data.user)
          );
        }
      });
    },
    goStaff() {
      this.$router.push("/StaffLogin");
    },
    loginDo() {
      this.$axios.post("/users/loginDo", this.login).then((response) => {
        if (response.data.code == 200) {
          this.$message.success("登录成功");
          this.$router.push("/Index");
          this.destroyed();
          sessionStorage.setItem(
            "user",
            JSON.stringify(response.data.data.user)
          );
        } else {
          this.$message.error("账号或密码有误，请检查后重新登录");
        }
      });
    },
    registerDo() {
      this.dialog.addshow = true;
    },
    addUser() {
      this.$axios.post("/users/registerDo", this.addForm).then((response) => {
        if (response.data.code == 200) {
          this.$message.success(response.data.massage);
          this.dialog.addshow = false;
          this.addForm = {};
        } else {
          this.$message.error(response.data.message);
        }
      });
    },

    keyDown(e) {
      //如果是回车则执行登录方法
      if (e.keyCode == 13) {
        this.loginDo();
      }
    },
    destroyed() {
      window.removeEventListener("keydown", this.keyDown, false);
    },
  },
  created() {
    window.addEventListener("keydown", this.keyDown);
  },
};
</script>

<style scoped>
.login-wrap {
  height: 990px;
  font-family: JetBrains Mono Medium;
  display: flex;
  align-items: center;
  justify-content: center;
  /* background-color: #0e92b3; */
  background: url("../assets/images/login.heic");
  background-size: 100% 100%;
}

.form-wrapper {
  width: 300px;
  background-color: rgba(41, 45, 62, 0.8);
  color: #fff;
  border-radius: 2px;
  padding: 50px;
}

.form-wrapper .header {
  text-align: center;
  font-size: 35px;
  text-transform: uppercase;
  line-height: 100px;
}

.form-wrapper .input-wrapper input {
  background-color: rgb(41, 45, 62);
  border: 0;
  width: 100%;
  text-align: center;
  font-size: 15px;
  color: #fff;
  outline: none;
}

.form-wrapper .input-wrapper input::placeholder {
  text-transform: uppercase;
}

.form-wrapper .input-wrapper .border-wrapper {
  background-image: linear-gradient(to right, #e8198b, #0eb4dd);
  width: 100%;
  height: 50px;
  margin-bottom: 20px;
  border-radius: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.form-wrapper .input-wrapper .border-wrapper .border-item {
  height: calc(100% - 4px);
  width: calc(100% - 4px);
  border-radius: 30px;
}

.form-wrapper .action {
  display: flex;
  justify-content: center;
}

.form-wrapper .action .btn {
  width: 60%;
  text-transform: uppercase;
  border: 2px solid #0e92b3;
  text-align: center;
  line-height: 50px;
  border-radius: 30px;
  cursor: pointer;
}

.form-wrapper .action .btn:hover {
  background-image: linear-gradient(120deg, #84fab0 0%, #8fd3f4 100%);
}

.form-wrapper .icon-wrapper {
  text-align: center;
  width: 60%;
  margin: 0 auto;
  margin-top: 20px;
  border-top: 1px dashed rgb(146, 146, 146);
  padding: 20px;
}

.form-wrapper .icon-wrapper i {
  font-size: 20px;
  border: 1px solid #fff;
  padding: 5px;
  border-radius: 20px;
}

.form-wrapper .icon-wrapper i:hover {
  background-color: #0e92b3;
}
</style>